package com.atguigu.petstore.app.service.impl;


import com.atguigu.petstore.app.service.SmsService;
import com.atguigu.petstore.common.constant.RedisConst;
import com.atguigu.petstore.common.util.HttpUtils;
import com.atguigu.petstore.common.util.NumberUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @Description
 * @create 2023-09-27 11:46
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void sendCode(String phone) {
        //1、生成随机号(随机的6位数)   0.0 and less than 1.0.
        String genNum = NumberUtils.genNnum(6);

        //2、手机号验证码绑定关系保存到redis、 登录用户带上验证码，我们就可以去redis核验；
        //redis: key: phone:code:手机号 = 验证码   过期时间：5分钟
        redisTemplate.opsForValue().set(RedisConst.PHONE_CODE +phone,genNum,5, TimeUnit.MINUTES);

        //3、发送短信
        sendSms(phone, genNum, 5);

    }


    private void sendSms(String phone, String code, Integer minute) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "93b7e19861a24c519a7548b17dc16d75";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:" + code + ",**minute**:" + minute);

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {

            //自己发送请求
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
